<template>
  <div class="container">
    <view-box ref="viewBox" body-padding-top="46px" body-padding-bottom="53px">
      <x-header class="my-header" >填写订单</x-header>
      <div style="min-height: 100%">
        <flexbox orient="vertical">
          <flexbox-item>
            <div class="flex-demo">
              <span class="icon" :class="icon"></span>
              <h4 class="item_title">{{Content.name}}</h4>
              <div class="item_des">{{Content.des}}</div>
            </div>
          </flexbox-item>
        </flexbox>
        <group>
          <popup-radio title="服务对象" :options="options" v-model="option" placeholder="请选择" :on-hide="chooseObj(option)"></popup-radio>
        </group>
        <group>
          <datetime v-model="startDate" @on-clear="getdate" format="YYYY-MM-DD HH:mm" placeholder="请选择" :title="$t('开始服务时间')"></datetime>
        </group>
        <group :title="'职称选择'">
          <radio :selected-label-style="{color: '#FF9900'}"  :options="radio" v-model="radioValue" @input="changeSid"></radio>
        </group>
        <group>
          <popup-picker title="购买数量(次数/小时)" :data="count" v-model="value" :placeholder="$t('')" @on-change="getSerTime"></popup-picker>
        </group>
        <group title="就医证明  至少选两项上传">
          <input id="js-file" type="file" accept="image/*" style="display:none">
          <cell title="医嘱" :value="doc_adviceName" is-link @click.native="uploadimg('doc_advice')">
          </cell>
          <cell title="处方" :value="recipeName" is-link @click.native="uploadimg('recipe')"></cell>
          <cell title="购药发票" :value="invoiceName" is-link @click.native="uploadimg('invoice')"></cell>
          <cell title="药品照片" :value="medicine_picName" is-link @click.native="uploadimg('medicine_pic')"></cell>
          <cell title="患者病例" :value="patient_caseName" is-link @click.native="uploadimg('patient_case')"></cell>
        </group>
        <group>
          <x-textarea :title="$t('备注')" v-model="description" :max="200" :placeholder="$t('选填')" :show-counter="false" :height="50" :rows="4" :cols="30"></x-textarea>
        </group>
      </div>
      <tabbar slot="bottom" id="tabbar">
        <tabbar-item>
          <span slot="label" style="color: rgb(255, 201, 8);font-weight: 400;font-size: 0.9rem"> ￥{{price}}</span>
        </tabbar-item>
        <tabbar-item style="background-color: rgb(255, 104, 140)"  @click.native="putOrder">
          <span slot="label" style="color: white;font-weight: 400;font-size: 0.9rem">提交</span>
        </tabbar-item>
      </tabbar>
    </view-box>
    <toast v-model="noPid" type="text" :time="1500" is-show-mask text="请选择服务对象" position="bottom"></toast>
    <toast v-model="noTime" type="text" :time="1500" is-show-mask text="请选择服务时间" position="bottom"></toast>
    <toast v-model="noPicture" type="text" :time="1500" is-show-mask text="至少上传两张就医证明" position="bottom"></toast>
  </div>
</template>

<script>
  import {  Toast,CellBox ,XInput,XTextarea,Radio,XSwitch,Picker,PopupPicker, Datetime, XButton , PopupRadio,ViewBox,XHeader,Flexbox, FlexboxItem, Divider,Tabbar, TabbarItem, Group, Cell  } from 'vux'
  import {  myFolder,bucket,appid,sid,skey,region,cos,successCallBack,errorCallBack,progressCallBack,taskReady} from '../../../static/js/cos.js'
  import '../../../static/js/jquery-3.2.1.min.js'
  import $ from 'jquery'
  export default {
    data(){
      return {
        normalSid:'',    //普通sid
        highSid:'',      //高级id
        comp_normalSid:'', //有陪护普通id
        comp_highSid:'',    //有陪护高级id
        normalList:'',      //普通list
        highList:'',        //高级list
        comp_normalList:'',    //有陪护普通list
        comp_highList:'',       //有陪护高级list
        icon:'',          //icon的class
        Content:'',         //服务内容
        count:[['1','2','3','4','5','6','7','8','9','10']],    //服务次数
        value: ['1'],       //默认次数
        radio: [ {key:'normalSid',value:'普通职称'}],
        radioValue: 'normalSid',    //默认职称
        slidList:'',          //子服务列表
        price:'0',             //最终价格
        plist:'',          //病患列表
        options:[{key:'添加病患信息',value:'添加病患信息'}],   //病患列表
        option:'',
        startDate:'',      //开始服务时间
        isLogin:false,      //是否显示未登录提示
        noPicture:false,      //就医证明是否有两张
        description:'',      //备注
        noPid:false,     //未选择病患
        noTime:false,      //未选择时间
        prove:[],
        doc_adviceName:'上传',       //医嘱
        recipeName:'上传',             //处方
        invoiceName:'上传',         //购药发票
        medicine_picName:'上传',        //药品照片
        patient_caseName:'选填',       //患者病例
        doc_advice:'',       //医嘱
        recipe:'',             //处方
        invoice:'',         //购药发票
        medicine_pic:'',        //药品照片
        patient_case:''         //患者病例
      }
    },
    mounted(){
      this.normalSid=this.$route.query.normalSid;
      this.highSid=this.$route.query.highSid;
      if(this.highSid!=undefined){
          this.radio.push({key:'highSid',value:'高级职称'})
      }
      this.icon=this.$route.query.icon;
      try{
        this.comp_normalSid=this.$route.query.comp_normalSid
        this.comp_highSid=this.$route.query.comp_highSid
        console.log(this.comp_normalSid)
        if(this.comp_normalSid!=undefined){                 //如果有陪护就添加陪护选项
          this.radio.push({key:'comp_normalSid',value:'有陪护普通职称'})
        }if(this.comp_highSid!=undefined){
          this.radio.push({key:'comp_highSid',value:'有陪护高级职称'})
        }
      }catch (err){
        console.log(err)
      }
      this.checkToken();
      this.initdata(this.normalSid);
      this.getPatient();
      this.getSlid()
    },
    methods:{
      checkToken(){         //检查登录状态
        this.Ajax('get','/javaapi/oauth2/token/status',{},(res)=>{
          if(res.body.sc=='20001'){
            this.isLogin=true
            this.$router.push({
              path:'/login',
              query:{
                normalSid: this.normalSid,
                highSid:this.highSid,
                icon:this.icon,
                originPath:'/order_details/ordering',
                isLogin:true
              }
            })
          }
        })
      },
      getPatient(){      //获取病患
        let data
        this.Ajax('get','/javaapi/patients',data,(body)=>{
          this.plist=body
          body.forEach((item)=>{
            this.options.push({key:item.pid,value:item.realName})
          })
        })
      },
      uploadimg(type){    //上传图片
        let source_url
        let geturl=this
        $('#js-file').off('change').on('change', function (e) {
          console.log(e.target.files[0].name);
          var file = e.target.files[0];
          var successCallBack = function (result) {
            let data=JSON.stringify(result)
            let obj=(new Function("return" + data))();
            switch (type){
              case 'doc_advice':
                geturl.doc_adviceName=e.target.files[0].name
                geturl.doc_advice=obj.data.source_url;
                break
              case 'recipe':
                geturl.recipeName=e.target.files[0].name
                geturl.recipe=obj.data.source_url;
                break
              case 'invoice':
                geturl.invoiceName=e.target.files[0].name
                geturl.invoice=obj.data.source_url;
                break
              case 'medicine_pic':
                geturl.medicine_picName=e.target.files[0].name
                geturl.medicine_pic=obj.data.source_url;
                break
              case 'patient_case':
                geturl.patient_caseName=e.target.files[0].name
                geturl.patient_case=obj.data.source_url;
                break
            }
//            geturl.form[dataname]=obj.data.source_url
//            geturl.$message({
//              message:'上传成功',
//              type:'success'
//            })
          };
          // 分片上传过程可能会有 op=upload_slice_list 的 POST 请求返回 404，不会影响上传：https://github.com/tencentyun/cos-js-sdk-v4/issues/16
          cos.uploadFile(successCallBack, errorCallBack, progressCallBack, bucket, myFolder + file.name, file, 0, taskReady);//insertOnly==0 表示允许覆盖文件 1表示不允许
          console.log(source_url)
//          this.form.download=source_url
          $('#js-file')[0].reset();
          return false;
        });

        setTimeout(function () {
          $('#js-file').click();
        }, 0);
        return false;
      },
      getdate(){          //转换年月日格式
        let now = new Date()
        let cmonth = now.getMonth() + 1
        let day = now.getDate()
        if (cmonth < 10) cmonth = '0' + cmonth
        if (day < 10) day = '0' + day
        this.startDate = now.getFullYear() + '-' + cmonth + '-' + day
      },
      initdata(sid){
        let data={}
        this.Ajax('get','/Mall/Service/detail/sid/'+sid,data,(res)=>{
          let content={}
          content.des=res.data.description
          content.name=res.data.name
          this.Content=content
        })
      },
      chooseObj(option){
        if(option=='添加病患信息'){
          this.$router.push('/add_patient')
        }
      },
      getSlid(){     //获取普通陪护与高级陪护的子服务列表
        let data={
          index:0,
          count:20
        }
        this.Ajax('post','/Mall/ServiceList/servicelist/sid/'+this.normalSid,data,(res)=>{
          this.normalList=res.dataList
          this.slidList=this.normalList
          let index=this.value[0]-1
          let price=this.normalList[index].price
          price=price.substring(price.length-2,0)
          this.price=price
        })
        this.Ajax('post','/Mall/ServiceList/servicelist/sid/'+this.highSid,data,(res)=>{
          this.highList=res.dataList
        })
        this.Ajax('post','/Mall/ServiceList/servicelist/sid/'+this.comp_normalSid,data,(res)=>{
          this.comp_normalList=res.dataList
        })
        this.Ajax('post','/Mall/ServiceList/servicelist/sid/'+this.comp_highSid,data,(res)=>{
          this.comp_highList=res.dataList
        })
      },
      changeSid(){     //选择职称
        let type=this.radioValue
        if(type=='normalSid'){
          this.slidList=this.normalList
          let index=this.value[0]-1
          let price=this.slidList[index].price
          price=price.substring(price.length-2,0)
          this.price=price
        }else if(type=='highSid'){
          this.slidList=this.highList
          let index=this.value[0]-1
          let price=this.slidList[index].price
          price=price.substring(price.length-2,0)
          this.price=price
        }else if(type=='comp_normalSid'){
          this.slidList=this.comp_normalList
          let index=this.value[0]-1
          let price=this.slidList[index].price
          price=price.substring(price.length-2,0)
          this.price=price
        }else if(type=='comp_highSid'){
          this.slidList=this.comp_highList
          let index=this.value[0]-1
          let price=this.slidList[index].price
          price=price.substring(price.length-2,0)
          this.price=price
        }
      },
      getSerTime(){
        let index=this.value-1
        let price=this.slidList[index].price
        price=price.substring(price.length-2,0)
        this.price=price
      },
      putOrder(){   //提交订单
        let prove,count=0
        prove=[4]
        prove[0]=this.doc_advice
        prove[1]=this.recipe
        prove[2]=this.invoice
        prove[3]=this.medicine_pic
        prove[4]=this.patient_case
        prove.forEach((item)=>{
          if(item){
            count++
          }
        })
        prove=prove.toString()
        if(this.option=="请选择"){
          this.noPid=true
        } else if(!this.startDate){
          this.noTime=true
        }else if(count<2){
          this.noPicture=true
        }
        else{
          let pid=this.option,loc,end_date_time,start_date_time,slid,description,name
          this.plist.forEach((item)=>{
            if(item.pid==pid){
              loc=item.address2Show
              name=item.realName
              pid=pid.toString()
            }
          })
          start_date_time=this.startDate.replace(/-/g,'/')
          start_date_time=new Date(start_date_time).getTime()
          end_date_time=start_date_time+3600000

          slid=this.slidList[this.value[0]-1].slid
          description=this.description
          let orderData={
            loc:loc,
            pid:pid,
            start_date_time:start_date_time,
            end_date_time:end_date_time,
            slid:slid,
            prove:prove,
            description:description,
            coupon:''
          }
          this.Ajax("post",'/Order/Order/order',orderData,(res)=>{
            let oid=res.data.oid
            orderData.oid=oid
            orderData.patient_name=name
            orderData.price=this.price
            orderData.datetime=res.data.datetime
            this.$router.push({
              path:'/order_details/order_pay/',
              query: orderData
            })
          })
        }
      }
    },
    components: {
      Toast,CellBox, XInput, XTextarea, Radio, XSwitch, Picker, PopupPicker, Datetime, XButton, Group, PopupRadio, ViewBox, XHeader, Flexbox, FlexboxItem, Divider, Tabbar, TabbarItem, Cell
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped  lang="stylus" rel="stylesheet/stylus">
  .flex-demo{
    min-height: 70px;
    background-color: white;
  }
  .content{
    padding: 1px 10px 1px 10px;
  }
  .content p{
    margin: 15px 0 15px 0;
  }
  .my-header {
    background-color: rgb(255, 104, 140);
    position: fixed;
    height: 46px;
    left: 0;
    top: 0;
    width: 100%;
    z-index: 100;
  }
  .icon
    display: inline-block;
    float left
    margin: 10px 5px 15px 20px;
    width: 50px;
    height: 50px;
    background-size: 45px 45px;
    background-repeat: no-repeat;
    &.visit_1
      background-image url('../mainpage/icons/visit/visit_1.imageset/visit_1.png')
    &.visit_2
      background-image url('../mainpage/icons/visit/visit_2.imageset/visit_2.png')
    &.visit_3
      background-image url('../mainpage/icons/visit/visit_3.imageset/visit_3.png')
    &.visit_4
      background-image url('../mainpage/icons/visit/visit_4.imageset/visit_4.png')
    &.visit_5
      background-image url('../mainpage/icons/visit/visit_5.imageset/visit_5.png')
    &.visit_6
      background-image url('../mainpage/icons/visit/visit_6.imageset/visit_6.png')
    &.visit_7
      background-image url('../mainpage/icons/visit/visit_7.imageset/visit_7.png')
    &.visit_8
      background-image url('../mainpage/icons/visit/visit_8.imageset/visit_8.png')
    &.visit_9
      background-image url('../mainpage/icons/visit/visit_9.imageset/visit_9.png')
    &.visit_10
      background-image url('../mainpage/icons/visit/visit_10.imageset/visit_10.png')
    &.visit_11
      background-image url('../mainpage/icons/visit/visit_11.imageset/visit_11.png')
    &.visit_12
      background-image url('../mainpage/icons/visit/visit_12.imageset/visit_12.png')
    &.visit_13
      background-image url('../mainpage/icons/visit/visit_13.imageset/visit_13.png')
    &.visit_14
      background-image url('../mainpage/icons/visit/visit_14.imageset/visit_14.png')
    &.visit_15
      background-image url('../mainpage/icons/visit/visit_15.imageset/visit_15.png')
    &.visit_16
      background-image url('../mainpage/icons/visit/visit_16.imageset/visit_16.png')
    &.visit_17
      background-image url('../mainpage/icons/visit/visit_17.imageset/visit_17.png')
    &.visit_18
      background-image url('../mainpage/icons/visit/visit_18.imageset/visit_18.png')
  .item_title
    display inline-block
    margin 10px 0 5px 0
    color black
    font-weight bold
  .item_des
    color gray
    font-size 12px
  #tabbar
    position fixed
    bottom 0
</style>
